<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Order extends FOX_Controller {

	function __construct ()
	{
		parent::__construct();
        $this->load->model('category_m');
        $this->load->model('member_m');
        $this->load->model('areas_m');
        $this->load->model('good_m');
        $this->load->model('order_m');
        $this->load->model('tmporder_m');
	}

	public function order(){
        // 获取所有的产品类型
        $data['cates'] = $this->category_m->get_cates_by_pid(0);
        $data['foot_menu'] = "order";
        $this->load->view('order',$data);
    }

    public function create_order(){

        $user_id = $this->session->userdata('user_id');
	    $post = $this->input->post();
        if(!isset($post['product_id']) || empty($post['product_id'])){
            echo json_encode(array(
                'status' => 400,
                "msg"=>"请选择产品",
            ));
            exit();
        }
        if(!isset($post['good_mum']) || empty($post['good_mum'])){
            echo json_encode(array(
                'status' => 400,
                "msg"=>"请填写产品数量",
            ));
            exit();
        }
        $len = count($post['category_id']);
        $orders = array();
        for ($i=0; $i < $len; $i++) {
            foreach ($_POST as $key => $value) {
                $data[$key] = $value[$i];
            }
            $orders[] = $data;
        }
        $order_no = $this->create_order_no();
        if(!empty($orders)) {
            $order_price = "0";
            foreach ($orders as $key => $val) {
                $orders[$key]['user_id'] = $user_id;
                // 根据商品id获取商品信息
                $good = $this->good_m->get_shop_goods_by_id($val['product_id']);
                $good_total_price = $val['good_mum'] * ($good['good_price'] * 100) / 100;
                $orders[$key]['good_price'] = $good_total_price;
                $order_price += $good_total_price;
                $orders[$key]['order_add_time'] = time();
                $orders[$key]['order_no'] = $order_no;
                $this->tmporder_m->add_tmp_orders($orders[$key]);
            }
            // 总订单表记录
            $service_fee = $order_price * ($this->config->item('service_tax') * 100) / 100;
            $order_data = array(
                'order_no' => $order_no,
                'user_id' => $user_id,
                'good_price' => $order_price,
                'order_add_time' => time(),
            );
            $order_data['service_fee'] = $service_fee;
            $order_data['order_price'] = $order_price + $service_fee;
            $order_id = $this->order_m->create_order($order_data);
            $arr = [
                [
                    "order_no" => $order_no
                ],
                [
                    "order_no" => $order_no,
                    "order_id" => $order_id,
                ],
            ];
            $this->db->update_batch("tmp_orders", $arr, "order_no");
            echo json_encode(array(
                'status' => 200,
                "msg"=>"提交成功",
                "url"=>site_url("order/order_other/".$order_no),
            ));
        }
    }
    public function order_other($order_no){
        if(!$order_no){ return false;}
        $this->session->unset_userdata("order_back_url");
        $user_id = $this->session->userdata('user_id');
        // 根据订单号获取订单
        $order = $this->order_m->get_shop_orders_by_order_no($order_no);
        $data['order'] = $order;
        $member = $this->user_m->get_user_by_user_id($user_id);
        $data['member'] = $member;
        // 读取默认地址
        $dress=$this->member_m->get_adress_by_user_id($user_id);
        if(!empty($dress)){
            $area =  $this->areas_m->get_area_by_id($dress['dress_province']);
            $area2 =  $this->areas_m->get_area_by_id($dress['dress_city']);
            $area3 =  $this->areas_m->get_area_by_id($dress['dress_district']);
            $data['dress_city'] = $area['area_name'].$area2['area_name'].$area3['area_name'].$dress['dress_udress'];
            $data['dress_id'] = $dress['dress_id'];
        }else{
            $data['dress_city'] = "请选择收货地址";
        }
        $this->load->view('order_other',$data);
    }

    public function order_pay(){
	    $post = $this->input->post();
        if(empty($post['order_no'])){ return false;}
        $data['is_kaipiao'] = $post['is_kaipiao'];
	    $data['is_songhuo'] = $post['is_songhuo'];
        $data['good_date'] = $post['good_date'];
        $data['remark'] = $post['remark'];
        // 根据订单号获取订单
        $order = $this->order_m->get_shop_orders_by_order_no($post['order_no']);
        $fee = $order['good_price'];
        // 服务费一定有
        $service_fee = $fee*($this->config->item('service_tax')*100)/100; // 服务费一定有
        $data['service_fee'] = $service_fee;
        $fee = $fee+$service_fee;
        // 获取送货费
        if($data['is_songhuo'] == 1){
            $orders = $this->tmporder_m->get_tmp_orders_by_order_no($post['order_no']);
            if(!empty($orders)){
                $songhuo_fee = "0";
                foreach ($orders as $key => $val){
                    $good = $this->good_m->get_shop_goods_by_id($val['product_id']);
                    $cateinfo=$this->category_m->get_category_by_id($good['good_category']);
                    $good_total_price_row = $val['good_mum']*($good['good_price']*100)/100;
                    $songhuo_fee += $good_total_price_row*($cateinfo['category_tax']*100)/100;
                }
                $data['songhuo_fee'] = $songhuo_fee;
                $fee = $fee+$songhuo_fee;
            }
        }
        // 获取开票费,(商品总额+服务费+送货费)*税点
        if($data['is_kaipiao'] == 1){
            $kaipiao_fee = $fee*($this->config->item('kaipiao_tax')*100)/100;
            $data['kaipiao_fee'] = $kaipiao_fee;
            $fee = $fee+$kaipiao_fee;
        }
        // 总订单表记录
        $data['order_price'] = $fee;
        // 更新送货，开票和服务费信息
        $this->order_m->sava_shop_orders_by_no($post['order_no'],$data);

        echo json_encode(array(
                'status' => 200,
                "msg"=>"提交成功",
                "url"=>site_url("order/pay_order_view/".$post['order_no']),
            ));
        exit();

    }

    public function pay_order_view($order_no){

        // 根据订单号获取订单
        $order = $this->order_m->get_shop_orders_by_order_no($order_no);
        // 后台计算总价格
        $notice = "含 ：";
        if($order['is_kaipiao'] == 1){
            $notice .= "10%税点, ";
        }
        // 送货费
        if($order['is_songhuo'] == 1){
            $notice .= $order['songhuo_fee']."送货费, ";
        }
        // 固定服务费
        $notice .= "2%服务费";
        $data['order'] = $order;
        $data['notice'] = $notice;
        $user_id = $this->session->userdata('user_id');
        $member = $this->user_m->get_user_by_user_id($user_id);
        $data['member'] = $member;
        $this->load->view('order_pay',$data);
    }

    public function pay_order(){

        $user_id = $this->session->userdata('user_id');
        $post = $this->input->post();
        $order_no = $post['order_no'];
        $pay_type = $post['pay_type'];//1销售贷2线下支付

        $order_info = $this->order_m->get_shop_orders_by_order_no($order_no);
        if($order_info['order_pay'] == 1 && $order_info['order_status'] > 0){
            echo json_encode(array('status' => 500,"msg"=>"该订单已经支付过了","url"=>site_url("order/records")));
            exit();
        }
        if($order_info['user_id'] == $user_id){
            // 获取余额信息
            $user_info=$this->user_m->get_user_by_user_id($user_id);
            $data = array(
                'order_pay'=>1,
                'order_status'=>2,
                'order_pay_type'=>$pay_type,
            );
            if($pay_type == 1){
                if($user_info['user_card_rz'] < 2){
                    echo json_encode(array('status' => 400,"msg"=>"您还没有开通销售贷"));
                    exit();
                }
                if($user_info['user_money_real']*100 < $order_info['order_price']*100){
                    echo json_encode(array('status' => 400,"msg"=>"销售贷余额不足"));
                    exit();
                }
            }
            $return = $this->order_m->sava_shop_orders_by_no($order_no,$data);
            if($return){
                if($pay_type == 1){
                    // 销售贷
                    $this->load->model('moneysale_m');
                    $this->load->model('moneylogs_m');
                    $rest = ($user_info['user_money_real']*100-$order_info['order_price']*100)/100;
                    $sale_log = array(
                        'user_id'=>$user_id,
                        'order_no'=>$order_no,
                        'order_cost'=>$order_info['order_price'],
                        'user_money_real'=>$rest,
                        'ctime'=>date("Y-m-d H:i:s"),
                    );
                    $this->moneysale_m->add_user_money_sale($sale_log);
                    // 变动日志
                    $money_log = array(
                        'user_id'=>$user_id,
                        'user_money_num'=>$order_info['order_price'],
                        'type'=>1,
                        'remark'=>"销售贷支付",
                        'ctime'=>date("Y-m-d H:i:s"),
                    );
                    $this->moneylogs_m->add_money_logs($money_log);
                    // 更新用户表余额
                    $this->user_m->update_user($user_id,array('user_money_real'=>$rest));
                }
                // 订单详情
                $tmporder_list = $this->tmporder_m->get_tmp_orders_by_order_no($order_no);
                $message_txt = "";
                if(!empty($tmporder_list)){
                    foreach ($tmporder_list as $k =>$v){
                        $good = $this->good_m->get_shop_goods_by_id($v['product_id']);
                        $message_txt = $good['good_title'].$good['good_memo']." ".$v['good_mum']."个;";
                    }
                }
                $massage = array(
                    'message_txt'=>"您已经成功下单 ".$message_txt,
                    'message_to_uid'=>$user_id,
                    'message_time'=>date("Y-m-d H:i:s"),
                );
                $this->message_m->add_massage($massage);
                echo json_encode(array(
                    'status' => 200,
                    "msg"=>"支付成功",
                    "url"=>site_url("order/pay_sure/".$order_no),
                ));
                exit();
            }else{
                echo json_encode(array('status' => 400,"msg"=>"支付失败"));
                exit();
            }
        }else{
            echo json_encode(array('status' => 400,"msg"=>"下单用户与当前用户不符合"));
            exit();
        }

    }

    public function pay_sure($order_no){

        if(!$order_no){ return false;}
        $order_info = $this->order_m->get_shop_orders_by_order_no($order_no);
        if(!empty($order_info)){
            $this->load->view('order_sure');
        }else{
            return false;
        }

    }

    public function records($page = 1){

        $user_id = $this->session->userdata('user_id');
        $this->load->library('pagination');
        $limit = 20;
        $config['uri_segment'] = 4;
        // $page = !empty($config['uri_segment'])?$config['uri_segment']:'0';
        $config['use_page_numbers'] = TRUE;
        $config['base_url'] = site_url('manage/orders/index/');
        $config['total_rows'] = $this->db->count_all('shop_orders');
        $config['per_page'] = $limit;
        $config['num_links'] = 10;
        $this->pagination->initialize($config);
        $start = ($page-1)*$limit;
        $data['pagination'] = $this->pagination->create_links();
        $orders = $this->order_m->get_all_orders_mobile($start,$limit,$user_id);
        if(!empty($orders)){
            foreach ($orders as $key=>$val){
                $notice = "含 ：";
                if($val['is_kaipiao'] == 1){
                    $notice .= "10%税点, ";
                }
                if($val['is_songhuo'] == 1){
                    $notice .= $val['songhuo_fee']."送货费, ";
                }
                $notice .= "2%服务费";
                $orders[$key]['notice'] = $notice;
                // 订单详情
                $tmporder_list = $this->tmporder_m->get_tmp_orders_by_order_no($val['order_no']);
                if(!empty($tmporder_list)){
                    foreach ($tmporder_list as $k =>$v){
                        $cateinfo=$this->category_m->get_category_by_id($v['category_id']);
                        $tmporder_list[$k]['category_name'] =  $cateinfo['category_name'];
                        $good = $this->good_m->get_shop_goods_by_id($v['product_id']);
                        $tmporder_list[$k]['good_title'] = $good['good_title'];
                        $tmporder_list[$k]['good_memo'] = $good['good_memo'];
                        $tmporder_list[$k]['good_content'] = $good['good_content'];
                        $tmporder_list[$k]['per_good_price'] = $good['good_price'];
                        $tmporder_list[$k]['good_part_number'] = $good['good_part_number'];
                    }
                }
                $orders[$key]['tmp_list'] = $tmporder_list;
            }
        }
        $data['orders'] = $orders;
//        pp($orders);exit();
        $this->load->view('user_order', $data);
    }


}
